﻿/// <reference path="../../jQuery/jquery.js"/>
/// <reference path="../../jQuery/jquery-calendar.js"/>
/// <reference path="../../jQuery/jquery.autocomplete.js"/>
/// <reference path="../../jQuery/jquery.autoloadselect.js"/>
/// <reference path="../../jQuery/jquery.wizard.js"/>
/// <reference path="../../json2.js"/>

var j=jQuery.noConflict();

jQuery(function($)
{
    var ListOfPerfs = [];
    var changed = false;

    $("#frmWizard").show();
    $("#waiting").hide();

    $('#hypEditTroupe').disable();
    $('#StatusBar').jnotifyInizialize({});
    
    // tabs-Productions  ===========================================================================================
    $('#TroupeId').selectChain({ target: '#season', url: siteRoot + '/Admin/SeasonsJson.rails' });
    $('#TroupeId').selectChain({ target: '#cbxStandard', url: siteRoot + '/Admin/SchedulesJson.rails' });
    $('#TroupeId').bind("change", function()
    {
        $(".wizard").wizard("enableNext");
        $("#hypEditTroupe").enable();
    });

    $('#season').bind("change", function() { ShowProdsGrid($('#season').val()); changed = false; });
    $("#dialogDelete").dialog({
        resizable: false,
        autoOpen: false,
        height: 250,
        width: 500,
        modal: true,
        overlay:
                {
                    backgroundColor: '#000',
                    opacity: 0.5
                },
        buttons:
            {
                'Yes- Delete it.': function()
                {
                    j.ajax({
                        url: siteRoot + "/Show/DeleteJson.rails",
                        data: { id: $('#ProductionId').val() },
                        dataType: 'json',
                        success: function()
                        {
                            $('#tblProductions').trigger("reloadGrid");
                            //jQuery.growl('Production deleted', 'Production deleted');
                            $('#StatusBar').jnotifyAddMessage({
                                text: 'Production deleted',
                                permanent: false,
                                type: 'message'
                            });
                        }
                    });
                    $(this).dialog('close');
                },
                'No - Cancel': function()
                {
                    $(this).dialog('close');
                }
            }
    });

    $('#btnDeleteProd').click(function()
    {
        $('#dialogDelete')
        .text("This will completely DELETE '{0}'.  Are you absolutely SURE?".format($('#txtPlay').val()))
        .dialog('open');
    }).disable();

    $('#btnAddProd').click(function()
    {
        $('#ProductionId').val(0);
        $('#VenueId').val(0);
        $('#txtPlay').val('');
        $('#PlayId').val(0);
        $('#txtAuthors').html('');
        $("#playComments").val('');
        $('.date-pick').val('');
        $('.wizard').wizard('moveNext');
        changed = true;
    });


    // tabs-Venues ===========================================================================================
    $('#lstCounties').selectChain({ target: '#lstVenues', url: siteRoot + '/Venue/ForCountyJson.rails' })
                                .hide().bind("change", function()
                                {
                                    $('#lstVenues').show();
                                    changed = true;
                                });

    $('#lstVenues').hide().bind("change", function()
    {
        SelectVenue($(this));
        changed = true;
    });
    $('#cbxOwnVenues').bind("change", function(event, fromCode)
    {
        var elm = $(this);
        if (elm.val() > '')
        {
            if (elm.val() == "0")
            {
                $('#lstCounties').show(); $('#lstVenues').show();
                $(".wizard").wizard("disableNext");
                $('#venueInfo').html("<td style='width:600px; height:59px;' ></td><td></td>");
            }
            else { $('#lstCounties').hide(); $('#lstVenues').hide(); SelectVenue(elm); }

            if (!fromCode)
                changed = true;
        }
    });

    // tabs-Play ===========================================================================================
    $("#dialogCreatePlay").dialog({
        resizable: false,
        autoOpen: false,
        height: 250,
        modal: true,
        overlay: { backgroundColor: '#000', opacity: 0.5 },
        buttons:
            {
                'Yes- Create it.': function()
                {
                    $(this).dialog('close');
                    $('#playComments').popupeditor({ length: 2000, title: $("#txtPlay").val(),
                        onSave: function()
                        {
                            j.ajax({
                                url: siteRoot + '/Play/AddJson.rails',
                                data: { title: $("#txtPlay").val(), comments: $('#playComments').val() },
                                dataType: 'json',
                                type: 'POST',
                                success: function(data, textStatus)
                                {
                                    $('#PlayId').val(data);
                                    $("#NewPlayNotice").show();
                                    $('#txtAuthors').text("New Play info saved.  Be sure to use the CastList feature to add playwright");
                                    $('#StatusBar').jnotifyAddMessage({
                                        text: "Play '" + $("#txtPlay").val() + "' has been created",
                                        permanent: false,
                                        type: 'message'
                                    });
                                    
                                }
                            });
                        }
                    });

                },
                'No - Cancel': function()
                {
                    $(this).dialog('close');
                }
            }
    });


    $("#txtPlay").autocomplete(siteRoot + "/Play/FindPlaysText.rails",
        {
            width: 500,
            mustMatch: false,
            autoFill: false,
            selectFirst: false,
            formatItem: function(row, pos, num, term)
            {
                var maxDesc = 84;
                var desc = (row[2].length > maxDesc) ? row[2].substr(0, maxDesc) + '...' : row[2];
                $('#PlayId').val("0");
                return row[1] + '<br/>(' + row[3] + ')<br/><i>' + desc + '</i>';
            },
            formatResult: function(data, value)
            {
                return data[1];
            }
        })
    .result(function(event, data, formatted)
    {
        // called if selction from list
        $("#PlayId").val(data[0]);
        $('#txtAuthors').html(data[3]);
        $("#playComments").attr('readonly', false).val(data[2]);

        changed = true;
        $(".wizard").wizard("enableNext");
    })
    .bind("nomatch.autocomplete", function()
    {
    })
    .blur(function()
    {
        if ($('#PlayId').val() > "0")
        {
            $("#NewPlayNotice").hide();
            if ($('#txtAuthors').html() == "")
                $("#NewPlayNotice").show();
        }
        else
        {
            $('#dialogCreatePlay')
                .text("This will create a new play called '{0}'.  Are you SURE?".format($('#txtPlay').val()))
                .dialog('open');
        }
        $(".wizard").wizard("enableNext");
    });
    $('#playComments').click(function()
    {
        $('#playComments').popupeditor({ length: 2000, title: $("#txtPlay").val(),
            onSave: function()
            {
                j.ajax({
                    url: siteRoot + '/Play/UpdateComment.rails',
                    data: { id: $("#PlayId").val(), comments: $('#playComments').val() },
                    dataType: 'json',
                    type: 'POST',
                    success: function(data, textStatus)
                    {
                        $('#StatusBar').jnotifyAddMessage({
                            text: "Comment for " + $("#txtPlay").val() + " has been updated",
                            permanent: false,
                            type: 'message'
                        });
                    }
                });
            }
        });
    });


    // tabs-Dates  ===========================================================================================
    $(".date-pick").datepicker(
            {
                showOn: 'both',
                buttonImageOnly: false,
                buttonText: '...'
            });

    $('#FirstPerformance').datepicker('option', 'onSelect', function()
    {
        var last = $('#LastPerformance');
        last.datepicker('option', 'minDate', $(this).datepicker('getDate'));
        last.datepicker('enable');
        changed = true;
    });

    var last = $('#LastPerformance');
    last.datepicker('option', 'onSelect', function()
    {
        changed = true;
        $(".wizard").wizard("enableNext");
    });

    $('#txtComments').click(function(evnt)
    {
        $('#txtComments').popupeditor({ length: 1000, title: "Production notes",
            onSave: function() { changed = true; }
        });
    });

    // tabs-SaveProduction==========================================================================================
    $('#btnSaveProd').click(function(event)
    {
        $('#btnSaveProd').disable();
        j.ajax({
            url: siteRoot + '/Show/EditDetails.rails',
            data: { id: $('#ProductionId').val(), troupeid: $('#TroupeId').val(),
                venueid: $('#VenueId').val(), playid: $('#PlayId').val(),
                start: $('#FirstPerformance').val(), end: $('#LastPerformance').val(), comments: $('#txtComments').val()
            },
            dataType: 'json',
            type: 'POST',
            success: function(data, textStatus)
            {
                if (data.ID == 0)
                {
                    $('#btnSaveProd').enable();
                    $('#StatusBar').jnotifyAddMessage({
                        text: 'An error Occured: ' + data.Title,
                        permanent: true,
                        type: 'error'
                    });

                }
                else
                {
                    $('#StatusBar').jnotifyAddMessage({
                        text: 'Production ' + data.Title + ' has been saved.  Click [Next] to add performance times',
                        permanent: false,
                        type: 'message'
                    });

                    changed = false;
                    $('#ProductionId').val(data.ID);
                }
            }
        });
        $(".wizard").wizard('enableNext');
        return false;
    });

    $(".btnCancel").click(function()
    {
        $(".wizard").wizard('gotoStep', 0);
        return false;
    });

    // tabs-Performances  ===========================================================================================
    $('#btnAddPerfs').click(function(event)
    {
        var currDate = new Date($('#FirstPerformance').val());
        currDate.addDays(($('#ddlDay').val() - currDate.getDay() + 7) % 7);
        var lastDate = new Date($('#LastPerformance').val());
        var time = $('#ddlTime').val();
        var newDates = [];
        while (currDate <= lastDate)
        {
            var newDate = new Date(currDate.getTime());
            newDates.push({ Date: newDate, Title: time, URL: '#' });
            currDate.addDays(7);
        }
        $.jMonthCalendar.AddEvents(newDates);
    });

    $('#btnInsert').click(function(event)
    {
        $.getJSON(siteRoot + '/Show/GetSchedulePerfsJson.rails', { ProductionId: $('#ProductionId').val(), SchedId: $('#cbxStandard').val() },
							function(data, textStatus)
							{
							    $.jMonthCalendar.AddEvents(data);
							}
						);
    });

    $("#btnSave").click(function(event)     // save Performaces
    {
        ListOfPerfs = _.select(ListOfPerfs, function(obj) { return !(obj instanceof Array && obj.length == 0); });
        var jsontext = JSON.stringify(ListOfPerfs);
        $.post(siteRoot + '/Show/SavePerfsJson.rails',
                            { ProductionId: $('#ProductionId').val(), Dates: jsontext },
							function(data, textStatus)
							{
							    //							    jQuery.growl("Success", 'Performance Dates saved.');
							    $('#StatusBar').jnotifyAddMessage({
							        text: 'Performance Dates saved.',
							        permanent: false,
							        type: 'message'
							    });

							},
							"json"
						);
    });

    $('#btnClear').click(function(event)
    {
        ListOfPerfs = [];
        $.jMonthCalendar.ReplaceEventCollection(ListOfPerfs);
        $.jMonthCalendar.AddEvents([]);
    });

    $(".AddProdId").click(function()
    {
        var href = $(this).attr("href") + "?id=" + $("#ProductionId").val();
        window.location = href;
        return false;
    });

    $(".wizard").wizard({ show: PreparePanel,
        historyEnabled: false,
        formPluginEnabled: true,
        validationEnabled: false
    });

    function PreparePanel(event, ui)
    {
        var element = ui.step[0];
        if (element == null)
            return;

        switch (element.id)
        {
            case 'tabs-Troupe':
                $("#hypEditTroupe").disable();
                var troupes = $("#TroupeId  option");
                if (troupes.length == 1)
                {
                    troupes[0].selected = true;
                    $('#TroupeId').disable();
                }
                if (troupes.anySelected())
                {
                    $(".wizard").wizard("enableNext");
                    $("#hypEditTroupe").enable();
                    $("#TroupeId").change();
                }
                break;

            case 'tabs-Productions':
                break;

            case 'tabs-Venue':
                $('#cbxOwnVenues')
                    .autoloadSelect(
                                {
                                    url: siteRoot + '/Venue/VenuesForProduction.rails',
                                    data: { TroupeID: $('#TroupeId').val(), ProductionID: $('#ProductionId').val() }
                                })
                     .trigger("change");
                break;

            case 'tabs-Play':
                if ($('#PlayId').val() > '')
                {
                    $.get(siteRoot + '/Play/InfoJson.rails', { PlayId: $('#PlayId').val() }, function(data)
                    {
                        $('#txtAuthors').html(data.Credits);
                        $('#playComments').val(data.Comments);
                        $(".wizard").wizard("enableNext");
                    }, "json");
                }
                $('#txtPlay').focus();
                break;

            case 'tabs-Dates':
                if ($('#FirstPerformance').val() == '')
                    $('#LastPerformance').datepicker('disable');
                else
                    $('#LastPerformance').datepicker('enable');

                if ($('#LastPerformance').val() > '')
                    $(".wizard").wizard("enableNext");
                else
                    $(".wizard").wizard("disableNext");
                break;

            case 'tabs-SaveProduction':
                if (changed)
                {
                    $("#lblSave").show();
                    $("#lblNoChanges").hide();
                    $("#btnSaveProd").enable();
                }
                else
                {
                    $("#lblSave").hide();
                    $("#lblNoChanges").show();
                    $("#btnSaveProd").disable();
                    $(".wizard").wizard("enableNext");
                }
                break;

            case 'tabs-Performances':
                $(".wizard").wizard("enableNext");
                $.getJSON(siteRoot + '/Show/GetPerfsJson.rails', { ProductionId: $('#ProductionId').val() },
							function(data, textStatus)
							{
							    var start = data.length > 0 ? data[0].Date : new Date($('#FirstPerformance').val());
							    $.jMonthCalendar.Initialize(
							    {
							        calendarStartDate: start,
							        width: 800,
							        height: 400,
							        onEventLinkClick: function(evnt)
							        {
							            var e = evnt;
							            var newPerfs = _.select(ListOfPerfs, function(dat)
							            {
							                return dat.Date != evnt.Date;
							            });
							            ListOfPerfs = newPerfs;
							            $.jMonthCalendar.ReplaceEventCollection(ListOfPerfs);
							            $.jMonthCalendar.AddEvents([]);
							            return false;
							            // delete current event
							        },
							        onDayCellDblClick: function(date, cell)
							        {
							            if (cell.data("active") === date)
							                return false;
							            cell.data("active", date);
							            var ddl = $('#ddlTime').clone();
							            ddl.prepend("<option value=' ' selected='selected'></option>");
							            ddl.val(' ');
							            cell.append(ddl);
							            ddl.change(function(evnt)
							            {
							                var time = $(this).val();
							                if (time != ' ')
							                {
							                    var newDate = { Date: date, Title: time, URL: '#' };
							                    cell.data("active", 0);

							                    $.jMonthCalendar.AddEvents(newDate);
							                    // add new single event
							                }
							                ddl.remove();
							            });
							        }
							    },
							    data);
							    ListOfPerfs = data;
							}
						);
        }
    }

    function ShowProdsGrid(datestr)
    {
        var gridimgpath = siteRoot + '/javascript/jQuery/jqGrid/themes/basic/images';

        $('#fragment-productions').html('<table  class="scroll" id="tblProductions"></table>');
        jQuery("#tblProductions").jqGrid({
            url: siteRoot + '/Admin/ProductionsJson.rails',
            postData: { TroupeID: $('#TroupeId').val(), Season: datestr },
            datatype: "json",
            colNames: ['Id', 'PlayId', 'VenueId', 'Title', 'At', 'From', 'To'],
            jsonReader: { repeatitems: false },
            colModel:
   	        [
   		        { name: 'ProductionId', index: 'ProductionId', hidden: true, editable: false },
   		        { name: 'PlayId', index: 'PlayId', hidden: true, editable: false },
   		        { name: 'VenueId', index: 'VenueId', hidden: true, editable: false },
   		        { name: 'Title', index: 'Title', width: 300, editable: false },
   		        { name: 'name', index: 'name', width: 200, editable: false },
   		        { name: 'FirstPerformance', index: 'FirstPerformance', width: 110, editable: false, datefmt: 'm/d/yyyy', sorttype: 'date' },
   		        { name: 'LastPerformance', index: 'LastPerformance', width: 110, editable: false, datefmt: 'm/d/yyyy', sorttype: 'date' }
   	        ],
            height: '200px',
            imgpath: gridimgpath,
            sortname: 'ProductionId',
            viewrecords: true,
            sortorder: "asc",
            caption: "Select production",
            onSelectRow: function(rowid)
            {
                var b = $("#tblProductions").getRowData(rowid);
                $('#ProductionId').val(b.ProductionId);
                $('#PlayId').val(b.PlayId);
                $('#txtPlay').val(b.Title);
                $('#FirstPerformance').val(b.FirstPerformance);
                $('#LastPerformance').val(b.LastPerformance);
                SelectVenueId(b.VenueId);
                $(".wizard").wizard("enableNext");
                $("#btnDeleteProd").enable();
                $("#btnAddCastlist1").enable();
                changed = false;
            }
        }).trigger("reloadGrid");
        $("#btnAddCastlist1").disable();
    }

    function SelectVenue(elm)
    {
        var vid = elm.val();
        SelectVenueId(vid);
        $(".wizard").wizard("enableNext");
    }
    function SelectVenueId(vid)
    {
        $('#VenueId').val(vid);
        $('#venueInfo').load(siteRoot + '/Venue/Info.rails', { VenueId: vid });
    }
})